<?php
namespace Operator\Model;

/**
 * 财务
 */
class FinanceModel extends BaseModel
{
    //订单退款处理
    public function refund()
    {
        //type 1 拒绝 2 通过
        $type         = I('type');
        $order_status = $type == 1 ? 3 : -5;
        $oid          = I('order_id');
        $data         = ['order_status' => $order_status, 'refund_record_time' => time()];
        //记录退款拒绝详情
        if ($type == 1) {
            // $refund_res = M('refund_record')->add(['order_id' => $oid,'refund_time' => time()]);
            // if( $refund_res === false){
            //     M()->rollback();
            //     return ['status' => -2, 'msg' => '退款拒绝详情记录失败'];
            // }
            $data['is_refund'] = 1;
        }

        M()->startTrans();
        $res = M('line_orders')
            ->where(['order_id' => $oid])
            ->save($data);

        //释放余位
        if ($type == 2) {
            $reset_res = D('SaleManger')->resetSeat($oid);
            if ($reset_res === false) {
                M()->rollback();
                return ['status' => -3, 'msg' => '释放余位失败'];
            }
        }

        if ($res === false) {
            M()->rollback();
            return ['status' => -1, 'msg' => '操作失败'];
        }

        M()->commit();
        return ['status' => 1, 'msg' => '操作成功'];
    }

    /**
     * 获取分销商结算列表
     */
    public function getResellerSettlementList($where)
    {
        // 查询满足要求的总记录数
        $count = M('line_orders')
            ->alias('o')
            ->field('count(*), sum(total_money) as sum')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            // ->join('INNER JOIN '.C('DB_PREFIX').'public_group g ON g.group_id=o.group_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'operator_line_reseller r ON r.reseller_id=o.manager_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'operator_line_supplier s ON s.supplier_id=l.supplier_id')
            ->where($where)
            ->find();
        // 分页
        $Page = new \Think\Page($count['count(*)'], 15);
        $show = $Page->show();

        // 查询
        $list = M('line_orders')->alias('o')
            ->field('r.reseller_name,o.end_need_pay,o.sales_id,r.reseller_sn,l.line_sn,l.group_num,l.line_name,s.supplier_name,o.total_num,o.adult_num,o.child_num,o.oldMan_num,o.total_money,o.close_time,l.source_type')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
        // ->join('INNER JOIN '.C('DB_PREFIX').'public_group g ON g.group_id=o.group_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'operator_line_reseller r ON r.reseller_id=o.manager_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'operator_line_supplier s ON s.supplier_id=l.supplier_id')
            ->where($where)
            ->order('o.order_id desc')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        //查询分销商
        $operator_id = session('operator_user.pid') ? session('operator_user.pid') : session('operator_user.operator_id');
        $reseller    = M('operator_line_reseller')
            ->field('reseller_id, reseller_name')
            ->where(['operator_id' => $operator_id])
            ->select();
        $reseller = $this->changeIndex($reseller);
        foreach ($list as $k => $v) {
            if (isset($reseller[$v['sales_id']])) {
                $list[$k]['sales'] = $reseller[$v['sales_id']]['reseller_name'];
            }
        }
        // 所有总的结算金额
        return ['list' => $list, 'show' => $show, 'all_total_end_need_pay' => round($count['sum'], 2)];

    }

    /**
     * Excel导出分销商结算列表-根据页面当前的筛选条件筛选
     */
    public function outResellerSettlementListExportExcel($where)
    {
        $list = M('line_orders')->alias('o')
            ->field('r.reseller_name,o.end_need_pay,o.sales_id,r.reseller_sn,l.line_sn,l.group_num,l.line_name,s.supplier_name,o.total_num,o.adult_num,o.child_num,o.total_money,o.close_time,l.source_type')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
        // ->join('INNER JOIN '.C('DB_PREFIX').'public_group g ON g.group_id=o.group_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'operator_line_reseller r ON r.reseller_id=o.manager_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'operator_line_supplier s ON s.supplier_id=l.supplier_id')
            ->where($where)
            ->order('o.order_id desc')
            ->select();
        //查询分销商
        $operator_id = session('operator_user.pid') ? session('operator_user.pid') : session('operator_user.operator_id');
        $reseller    = M('operator_line_reseller')
            ->field('reseller_id, reseller_name')
            ->where(['operator_id' => $operator_id])
            ->select();
        $reseller = $this->changeIndex($reseller);
        foreach ($list as $k => $v) {
            $list[$k]['close_time'] = $v['colse_time'] ? date('Y-m-d', $v['colse_time']) : '未结算';
            if (isset($reseller[$v['sales_id']])) {
                $list[$k]['sales'] = $reseller[$v['sales_id']]['reseller_name'];
            }

        }
        $expCellName = array(
            array('reseller_name', '分销商'),
            array('reseller_sn', '分销商编号'),
            array('line_sn', '线路编号'),
            array('group_num', '团号'),
            array('line_name', '线路名称'),
            array('supplier_name', '供应商'),
            array('adult_num', '成人人数'),
            array('child_num', '儿童人数'),
            array('total_money', '总结算金额'),
            array('sales', '操作人'),
        );

        $fileName = '分销商结算表';
        D('ExportExcel')->exportExcels($fileName, $expCellName, $list);
    }

    /**
     * 获取销售订单结算列表
     */
    public function getSettlementList($where)
    {
        // 查询满足要求的总记录数
        $count = M('line_orders')->alias('o')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join("__LINE_RESELLER_PRICE__ as p on p.line_id = o.line_id and p.reseller_id = o.manager_id and ((p.reseller_id = o.manager_id and o.order_type=rp_type) or rp_type = 0)")
            ->where($where)
            ->getField('count(*)');
        // 分页
        $Page = new \Think\Page($count, 15);
        $show = $Page->show();
        // 查询
        $list = M('line_orders')->alias('o')
            ->field('o.*,l.line_name,l.source_type,l.group_num,p.adult_price,p.child_price,p.oldman_price,origin_line_id')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join("__LINE_RESELLER_PRICE__ as p on p.line_id = o.line_id and ((p.reseller_id = o.manager_id and o.order_type=rp_type) or rp_type = 0)")
            ->where($where)
            ->order('o.order_id desc')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->arrangeData($list);

        return ['list' => $list, 'show' => $show];

    }

    /**
     * 整理数据
     * 将对应的销售人、负责人、城市的id换成中文
     * @param  [array] &$list
     */
    private function arrangeData(&$list)
    {
        $ms   = D('Staff');
        $shop = $this->changeIndex($ms->getSomeStaff());
        foreach ($list as $k => $v) {
            $list[$k]['create_time']        = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
            $list[$k]['refund_time']        = $v['refund_time'] ? date('Y-m-d H:i:s', $v['refund_time']) : '';
            $list[$k]['refund_record_time'] = $v['refund_record_time'] ? date('Y-m-d H:i:s', $v['refund_record_time']) : '';
             $list[$k]['line_name']   .=  ($v['origin_line_id'] ? '' : '(自营)') ;
            // if ($v['order_type'] == 1) {
            //     $list[$k]['manager']   = $shop[$v['manager_id']]['operator_name'];
            //     $list[$k]['sales']     = $shop[$v['sales_id']]['operator_name'];
            //     $list[$k]['operation'] = $shop[$v['sales_id']]['operator_name'];
            //     $list[$k]['store']     = $shop[$v['manager_id']]['store_name'];
            // } else {
            $list[$k]['manager']   = $shop[$v['manager_id']]['reseller_name'];
            $list[$k]['sales']     = $shop[$v['sales_id']]['reseller_name'];
            $list[$k]['operation'] = $shop[$v['sales_id']]['reseller_name'];
            $list[$k]['reseller']  = $shop[$v['manager_id']]['reseller_name'];
            // }
        }

    }

    /**
     * 根据订单ID获取发票信息
     */
    public function getOrdersReceiptById($id)
    {
        // 获取发票信息
        $rs = M('public_receipt')->where(array('order_id' => $id))->select();
        return $rs[0];

    }

    /**
     * 批量结算订单-人民币
     */
    public function batchSettlement($data)
    {
        $ids = explode(',', $data['order_ids']);
        foreach ($ids as $key => $id) {
            if ($id) {
                // 结算时间
                $close_time = time();
                M('line_orders')->where(['order_id' => $id])->setField(['order_status' => 2, 'close_time' => $close_time]);
            }
        }
        return array('status' => 1);
    }
    /**
     * 单个订单结算-人民币
     */
    public function singleSettlement($data)
    {
        // 结算时间
        $close_time = time();
        return M('line_orders')->where(['order_id' => $data['order_id']])->setField(['order_status' => 2, 'close_time' => $close_time]);
    }

    /**
     * 单个订单结算-外币
     */
    public function singleForeignSettlement($data)
    {
        // 结算时间
        $close_time = time();
        return M('line_orders')->where(['order_id' => $data['order_id']])->setField(['order_status' => 2, 'end_need_pay' => $data['end_need_pay'], 'settlement_rate' => $data['settlement_rate'], 'close_time' => $close_time]);
    }

    /**
     * 获取发票列表
     */
    public function getBillList($where)
    {
        // 缓存筛选条件
        // session('BILL_WHERE',$where);
        //查询条件 用于区分运营商与运营商门店订单
        $conf = (session('operator_user.pid') ? ' and manger_id = ' : ' and o.operator_id = ') . session('operator_user.operator_id');
        // 查询满足要求的总记录数
        $count = M('public_receipt')->alias('r')
        // ->field('r.*,o.order_num,o.need_pay,l.line_name,t.tourists_phone')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'line_orders o ON o.order_id=r.order_id ' . $conf)
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'public_tourists t ON t.tourists_id=o.contact_id')
            ->where($where)
            ->getField('count(*)');
        // 分页
        $Page = new \Think\Page($count, 15); // 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show(); // 分页显示输出
        // 查询
        $list = M('public_receipt')->alias('r')
            ->field('r.*,o.order_num,o.need_pay,l.line_name,t.tourists_phone')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'line_orders o ON o.order_id=r.order_id ' . $conf)
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'public_tourists t ON t.tourists_id=o.contact_id')
            ->where($where)
            ->order('r.open_time desc')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        return ['list' => $list, 'show' => $show];
    }

    /**
     * 获取员工销售业绩列表
     */
    public function getStaffSalesList($where)
    {
        // 查询满足要求的总记录数
        $count = M('line_orders')
            ->alias('o')
            ->field('count(*),sum(total_money) as sum')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'operator_line_reseller u ON u.reseller_id =o.manager_id ')
            ->where($where)
            ->find();
        // 分页
        $Page = new \Think\Page($count['count(*)'], 15); // 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show(); // 分页显示输出
        // 查询
        $list = M('line_orders')->alias('o')
            ->field('o.order_num,o.create_time,o.total_money,l.line_name,sales_id,manager_id')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'operator_line_reseller u ON u.reseller_id =o.manager_id ')
            ->where($where)
            ->order('o.order_id desc')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->staffSaleArrangeList($list);
        return ['list' => $list, 'all_total_money' => round($count['sum'], 2), 'show' => $show];
    }

    public function staffSaleArrangeList(&$list)
    {
        $staff = $this->changeIndex(D('Staff')->getSomeStaff(['shop_or_reseller' => 1]));
        foreach ($list as $k => $v) {
            $list[$k]['name'] = $staff[$v['manager_id']]['reseller_name'] . '：<br/>' . $staff[$v['sales_id']]['reseller_name'];
        }
    }

    //Excel导出员工销售订单数据
    public function outPerformanceExcel($where)
    {
        // 查询
        $list = M('line_orders')->alias('o')
            ->field('o.order_num,o.create_time,o.total_money,l.line_name,sales_id,manager_id')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'operator_line_reseller u ON u.reseller_id =o.manager_id ')
            ->where($where)
            ->order('o.order_id desc')
            ->select();
        $staff = $this->changeIndex(D('Staff')->getSomeStaff(['shop_or_reseller' => 1]));
        foreach ($list as $k => $v) {
            $list[$k]['create_time']   = date('Y-m-d', $v['create_time']);
            $list[$k]['order_num']     = $v['order_num'] . ' ';
            $list[$k]['operator_name'] = $staff[$v['manager_id']]['reseller_name'] . "：\n" . $staff[$v['sales_id']]['reseller_name'];
        }

        $expCellName = array(
            ['order_num', '订单号'],
            ['line_name', '线路名称'],
            ['create_time', '下单日期'],
            ['total_money', '订单总额'],
            ['operator_name', '销售人员'],
        );

        $fileName = '员工销售业绩';
        D('ExportExcel')->exportExcels($fileName, $expCellName, $list);
    }

    /**
     * Excel导出发票列表-根据页面当前的筛选条件筛选
     */
    public function outBillListExportExcel($where)
    {
        // $where = session('BILL_WHERE');
        $conf = (session('operator_user.pid') ? ' and manger_id = ' : ' and o.operator_id = ') . session('operator_user.operator_id');
        $list = M('public_receipt')->alias('r')
            ->field('r.*,o.order_num,o.need_pay,l.line_name,t.tourists_phone')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'line_orders o ON o.order_id=r.order_id ' . $conf)
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'public_tourists t ON t.tourists_id=o.contact_id')
            ->where($where)
            ->order('r.open_time desc')
        // ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['order_num'] .= ' ';
            $list[$k]['open_time'] = date('Y-m-d', $v['open_time']);
        }
        $expCellName = array(
            array('order_num', '订单号'),
            array('line_name', '线路名称'),
            array('need_pay', '销售价'),
            array('receipt_code', '发票代码'),
            array('receipt_num', '发票号码'),
            array('receipt_amount', '发票金额'),
            array('receipt_rise', '发票抬头'),
            array('receipt_content', '发票内容'),
            array('open_time', '开票时间'),
            array('open_user', '开据人'),
            array('remarks', '备注'),
        );

        $fileName = '发票统计表';
        D('ExportExcel')->exportExcels($fileName, $expCellName, $list);
    }

    /**
     * Excel导出销售结算单列表-根据页面当前的筛选条件筛选
     */
    public function outSettlementListExportExcel($where)
    {
        $list = M('line_orders')->alias('o')
            ->field('o.*,l.line_name,l.source_type,l.group_num,p.adult_price,p.child_price,p.oldman_price')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join("__LINE_RESELLER_PRICE__ as p on p.line_id = o.line_id and ((p.reseller_id = o.manager_id and o.order_type=rp_type) or rp_type = 0)")
            ->where($where)
            ->order('o.order_id desc')
            ->select();
        $this->arrangeData($list);
        foreach ($list as $k => $v) {
            $list[$k]['order_info'] = "订单号：{$v['order_num']}\n团号：{$v['group_num']}\n线路名称：{$v['line_name']}";
            $list[$k]['peopel']     = "成：{$v['adult_num']}\n儿童：{$v['child_num']}\n老人：{$v['oldMan_num']}\n合计：{$v['total_num']}人";
            $list[$k]['shop']       = $v['store'] ? $v['store'] : $v['reseller'];
            $list[$k]['price']      = "成人：{$v['adult_price']}\n儿童：{$v['child_price']}\n老人：{$v['oldman_price']}";
        }
        $expCellName = array(
            array('order_info', '订单信息'),
            array('peopel', '预订人数'),
            array('shop', '分销/门店'),
            array('price', '销售单价'),
            array('sales', '销售人'),
            array('close_money', '结算总金额'),
            array('currency_type', '币种'),
            array('settlement_rate', '汇率'),
            array('end_need_pay', '实收人民币'),
            array('create_time', '下单时间'),
            array('operation', '操作人'),
        );
        switch (I('order_status')) {
            case 2:
                $fileName = '销售订单已审核表';
                break;
            case -3:
                array_splice($expCellName, 6, 4, [['back_money', '退款金额'], ['refund_time', '申请退款时间']]);
                $fileName = '销售订单待退款表';
                break;
            case -5:
                array_splice($expCellName, 6, 4, [['back_money', '退款金额'], ['refund_record_time', '退款时间']]);
                $fileName = '销售订单已退款表';
                break;
            default:
                $fileName = '销售订单待审核表';
                break;
        }
        D('ExportExcel')->exportExcels($fileName, $expCellName, $list);
    }

}
